<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * Treacle File Uploading Class file
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package libraries
 */
/**
 * 文件上传
 * @package libraries
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
class TUpload
{
	private $max_size		= 0;
	private $max_width		= 0;
	private $max_height		= 0;
	private $allowed_types	= "";
	private $file_temp		= "";
	private $file_name		= "";
	private $orig_name		= "";
	private $file_type		= "";
	private $file_size		= "";
	private $file_ext		= "";
	private $upload_path	= "";
	private $overwrite		= FALSE;
	private $encrypt_name	= FALSE;
	private $is_image		= FALSE;
	private $image_width	= '';
	private $image_height	= '';
	private $image_type		= '';
	private $image_size_str	= '';
	private $error_msg		= array();
	private static $mimes	= array();
	private $remove_spaces	= TRUE;
	private $xss_clean		= FALSE;
	private $temp_prefix	= "temp_file_";
	/**
	 * 构造函数
	 * 
	 * @access	public
	 */
	public function __construct($props = array())
	{
		if (count($props) > 0)
		{
			$this->initialize($props);
		}
	}
	/**
	 * 初始化选项
	 * 
	 * @access	public
	 * @param	array
	 * @return	void
	 */	
	public function initialize($config = array())
	{
		$defaults = array(
		'max_size'			=> 0,
		'max_width'			=> 0,
		'max_height'		=> 0,
		'allowed_types'		=> "",
		'file_temp'			=> "",
		'file_name'			=> "",
		'orig_name'			=> "",
		'file_type'			=> "",
		'file_size'			=> "",
		'file_ext'			=> "",
		'upload_path'		=> "",
		'overwrite'			=> FALSE,
		'encrypt_name'		=> FALSE,
		'is_image'			=> FALSE,
		'image_width'		=> '',
		'image_height'		=> '',
		'image_type'		=> '',
		'image_size_str'	=> '',
		'error_msg'			=> array(),
		'mimes'				=> array(),
		'remove_spaces'		=> TRUE,
		'xss_clean'			=> FALSE,
		'temp_prefix'		=> "temp_file_"
		);
		foreach ($defaults as $key => $val)
		{
			if (isset($config[$key]))
			{
				$method = 'set_'.$key;
				if (method_exists($this, $method))
				{
					$this->$method($config[$key]);
				}
				else
				{
					$this->$key = $config[$key];
				}
			}
			else
			{
				$this->$key = $val;
			}
		}
	}

	/**
	 * 执行文件上传
	 * 
	 * @access	public
	 * @param $field 表单file域的name
	 * @return	bool
	 */	
	public function do_upload($field = 'userfile')
	{
		// Is $_FILES[$field] set? If not, no reason to continue.
		if ( ! isset($_FILES[$field]))
		{
			$this->set_error('upload_userfile_not_set');
			return FALSE;
		}
		// Is the upload path valid?
		if ( ! $this->validate_upload_path())
		{
			return FALSE;
		}
		// Was the file able to be uploaded? If not, determine the reason why.
		if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
		{
			$error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
			switch($error)
			{
				case 1  :   $this->set_error('upload_file_exceeds_limit');
				break;
				case 3  :   $this->set_error('upload_file_partial');
				break;
				case 4  :   $this->set_error('upload_no_file_selected');
				break;
				default :   $this->set_error('upload_no_file_selected');
				break;
			}
			return FALSE;
		}
		// Set the uploaded data as class variables
		$this->file_temp = $_FILES[$field]['tmp_name'];
		$this->file_name = $_FILES[$field]['name'];
		$this->file_size = $_FILES[$field]['size'];
		$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
		$this->file_type = strtolower($this->file_type);
		$this->file_ext	 = $this->get_extension($_FILES[$field]['name']);

		// Convert the file size to kilobytes
		if ($this->file_size > 0)
		{
			$this->file_size = round($this->file_size/1024, 2);
		}
		// Is the file type allowed to be uploaded?
		if ( ! $this->is_allowed_filetype())
		{
			$this->set_error('upload_invalid_filetype');
			return FALSE;
		}
		// Is the file size within the allowed maximum?
		if ( ! $this->is_allowed_filesize())
		{
			$this->set_error('upload_invalid_filesize');
			return FALSE;
		}
		// Are the image dimensions within the allowed size?
		// Note: This can fail if the server has an open_basdir restriction.
		if ( ! $this->is_allowed_dimensions())
		{
			$this->set_error('upload_invalid_dimensions');
			return FALSE;
		}
		// Sanitize the file name for security
		$this->file_name = $this->clean_file_name($this->file_name);

		// Remove white spaces in the name
		if ($this->remove_spaces == TRUE)
		{
			$this->file_name = preg_replace("/\s+/", "_", $this->file_name);
		}
		/*
		* Validate the file name
		* This public function appends an number onto the end of
		* the file if one with the same name already exists.
		* If it returns false there was a problem.
		*/
		$this->orig_name = $this->file_name;
		if ($this->overwrite == FALSE)
		{
			$this->file_name = $this->set_filename($this->upload_path, $this->file_name);

			if ($this->file_name === FALSE)
			{
				return FALSE;
			}
		}
		/*
		* Move the file to the final destination
		* To deal with different server configurations
		* we'll attempt to use copy() first.  If that fails
		* we'll use move_uploaded_file().  One of the two should
		* reliably work in most environments
		*/
		if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
		{
			if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
			{
				$this->set_error('upload_destination_error');
				return FALSE;
			}
		}
		/*
		* Run the file through the XSS hacking filter
		* This helps prevent malicious code from being
		* embedded within a file.  Scripts can easily
		* be disguised as images or other file types.
		*/
		if ($this->xss_clean == TRUE)
		{
			$this->do_xss_clean();
		}
		/*
		* Set the finalized image dimensions
		* This sets the image width/height (assuming the
		* file was an image).  We use this information
		* in the "data" function.
		*/
		$this->set_image_properties($this->upload_path.$this->file_name);
		return TRUE;
	}
	/**
	 * 返回上传文件信息
	 * 
	 * @access	public
	 * @return	array
	 */	
	public function data()
	{
		return array (
		'file_name'			=> $this->file_name,
		'file_type'			=> $this->file_type,
		'file_path'			=> $this->upload_path,
		'full_path'			=> $this->upload_path.$this->file_name,
		'raw_name'			=> str_replace($this->file_ext, '', $this->file_name),
		'orig_name'			=> $this->orig_name,
		'file_ext'			=> $this->file_ext,
		'file_size'			=> $this->file_size,
		'is_image'			=> $this->is_image(),
		'image_width'		=> $this->image_width,
		'image_height'		=> $this->image_height,
		'image_type'		=> $this->image_type,
		'image_size_str'	=> $this->image_size_str,
		);
	}
	/**
	 * 设置上传路径
	 * 
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public function set_upload_path($path)
	{
		$this->upload_path = $path;
	}
	/**
	 * 设置文件名
	 * 
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	string
	 */	
	public function set_filename($path, $filename)
	{
		if ($this->encrypt_name == TRUE)
		{
			mt_srand();
			$filename = md5(uniqid(mt_rand())).$this->file_ext;
		}
		if ( ! file_exists($path.$filename))
		{
			return $filename;
		}
		$filename = str_replace($this->file_ext, '', $filename);
		$new_filename = '';
		for ($i = 1; $i < 100; $i++)
		{
			if ( ! file_exists($path.$filename.$i.$this->file_ext))
			{
				$new_filename = $filename.$i.$this->file_ext;
				break;
			}
		}
		if ($new_filename == '')
		{
			$this->set_error('upload_bad_filename');
			return FALSE;
		}
		else
		{
			return $new_filename;
		}
	}
	/**
	 * 设置文件最大值
	 * 
	 * @access	public
	 * @param	integer
	 * @return	void
	 */	
	public function set_max_filesize($n)
	{
		$this->max_size = ( ! eregi("^[[:digit:]]+$", $n)) ? 0 : $n;
	}
	/**
	 * 设置图像最大宽度
	 *
	 * @access	public
	 * @param	integer
	 * @return	void
	 */	
	public function set_max_width($n)
	{
		$this->max_width = ( ! eregi("^[[:digit:]]+$", $n)) ? 0 : $n;
	}
	/**
	 * 设置图像最大高度
	 * 
	 * @access	public
	 * @param	integer
	 * @return	void
	 */	
	public function set_max_height($n)
	{
		$this->max_height = ( ! eregi("^[[:digit:]]+$", $n)) ? 0 : $n;
	}
	/**
	 * 设置允许的文件类型
	 * 
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public function set_allowed_types($types)
	{
		$this->allowed_types = explode('|', $types);
	}
	/**
	 * Set Image Properties
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public function set_image_properties($path = '')
	{
		if ( ! $this->is_image())
		{
			return;
		}
		if (function_exists('getimagesize'))
		{
			if (FALSE !== ($D = @getimagesize($path)))
			{
				$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');

				$this->image_width		= $D['0'];
				$this->image_height		= $D['1'];
				$this->image_type		= ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
				$this->image_size_str	= $D['3'];  // string containing height and width
			}
		}
	}
	/**
	 * Set XSS Clean
	 * 
	 * @access	public
	 * @param	bool
	 * @return	void
	 */
	public function set_xss_clean($flag = FALSE)
	{
		$this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
	}
	/**
	 * 验证是否是图片
	 * 
	 * @access	public
	 * @return	bool
	 */	
	public function is_image()
	{
		// IE will sometimes return odd mime-types during upload, so here we just standardize all
		// jpegs or pngs to the same file type.
		$png_mimes  = array('image/x-png');
		$jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');
		if (in_array($this->file_type, $png_mimes))
		{
			$this->file_type = 'image/png';
		}
		if (in_array($this->file_type, $jpeg_mimes))
		{
			$this->file_type = 'image/jpeg';
		}
		$img_mimes = array(
		'image/gif',
		'image/jpeg',
		'image/png',
		);
		return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
	}
	/**
	 * 验证允许文件类型
	 * 
	 * @access	public
	 * @return	bool
	 */	
	public function is_allowed_filetype()
	{
		if (count($this->allowed_types) == 0)
		{
			$this->set_error('upload_no_file_types');
			return FALSE;
		}
		foreach ($this->allowed_types as $val)
		{
			$mime = $this->mimes_types(strtolower($val));

			if (is_array($mime))
			{
				if (in_array($this->file_type, $mime, TRUE))
				{
					return TRUE;
				}
			}
			else
			{
				if ($mime == $this->file_type)
				{
					return TRUE;
				}
			}
		}
		return FALSE;
	}
	/**
	 * 验证允许的文件大小
	 * 
	 * @access	public
	 * @return	bool
	 */	
	public function is_allowed_filesize()
	{
		if ($this->max_size != 0  AND  $this->file_size > $this->max_size)
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	/**
	 * 验证图片宽和高
	 * 
	 * @access	public
	 * @return	bool
	 */	
	public function is_allowed_dimensions()
	{
		if ( ! $this->is_image())
		{
			return TRUE;
		}
		if (function_exists('getimagesize'))
		{
			$D = @getimagesize($this->file_temp);
			if ($this->max_width > 0 AND $D['0'] > $this->max_width)
			{
				return FALSE;
			}
			if ($this->max_height > 0 AND $D['1'] > $this->max_height)
			{
				return FALSE;
			}
			return TRUE;
		}
		return TRUE;
	}
	/**
	 * 验证上传路径
	 * 
	 * @access	public
	 * @return	bool
	 */	
	public function validate_upload_path()
	{
		if ($this->upload_path == '')
		{
			$this->set_error('upload_no_filepath');
			return FALSE;
		}
		if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
		{
			$this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
		}
		if ( ! @is_dir($this->upload_path))
		{
			$this->set_error('upload_no_filepath');
			return FALSE;
		}
		if ( ! is_writable($this->upload_path))
		{
			$this->set_error('upload_not_writable');
			return FALSE;
		}
		$this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/",  $this->upload_path);
		return TRUE;
	}
	/**
	 * 分解文件扩展名
	 * 
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
	public function get_extension($filename)
	{
		$x = explode('.', $filename);
		return '.'.end($x);
	}
	/**
	 * 过滤文件名中的非法字符
	 * @access	public
	 * @param	string
	 * @return	string
	 */		
	public function clean_file_name($filename)
	{
		$bad = array(
		"<!--",
		"-->",
		"'",
		"<",
		">",
		'"',
		'&',
		'$',
		'=',
		';',
		'?',
		'/',
		"%20",
		"%22",
		"%3c",		// <
		"%253c", 	// <
		"%3e", 		// >
		"%0e", 		// >
		"%28", 		// (
		"%29", 		// )
		"%2528", 	// (
		"%26", 		// &
		"%24", 		// $
		"%3f", 		// ?
		"%3b", 		// ;
		"%3d"		// =
		);
		foreach ($bad as $val)
		{
			$filename = str_replace($val, '', $filename);
		}
		return $filename;
	}
	/**
	 * Runs the file through the XSS clean function
	 *
	 * This prevents people from embedding malicious code in their files.
	 * I'm not sure that it won't negatively affect certain files in unexpected ways,
	 * but so far I haven't found that it causes trouble.
	 *
	 * @access	public
	 * @return	void
	 */	
	public function do_xss_clean()
	{
		$file = $this->upload_path.$this->file_name;
		if (filesize($file) == 0)
		{
			return FALSE;
		}
		if (($data = @file_get_contents($file)) === FALSE)
		{
			return FALSE;
		}
		if ( ! $fp = @fopen($file, 'r+b'))
		{
			return FALSE;
		}
		//		$data = Treacle::get_instance()->input->xss_clean($data);
		flock($fp, LOCK_EX);
		fwrite($fp, $data);
		flock($fp, LOCK_UN);
		fclose($fp);
	}
	/**
	 * Set an error message
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public function set_error($msg)
	{
		$this->error_msg[] = $msg;
	}
	/**
	 * Display the error message
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	string
	 */	
	public function display_errors($open = '<p>', $close = '</p>')
	{
		$str = '';
		foreach ($this->error_msg as $val)
		{
			$str .= $open.$val.$close;
		}
		return $str;
	}
	/**
	 * List of Mime Types
	 * 
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
	public function mimes_types($mime)
	{
		if (count($this->mimes) == 0)
		{
			if (@include(APPPATH.'config/mimes'.EXT))
			{
				$this->mimes = $mimes;
				unset($mimes);
			}
		}
		return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Sat Nov 10 14:05:00 CST 2007
+--------------------------------------------------------------------------
*/
?>